#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using TVC.Layout;
using System.Xml;
using System.IO;
using BUS;
using DTO;
using QueryBuilder;
using TVC.Report;
using FlexCel.Core;
using TVC.Modules.Rep;

#endregion

namespace TVC.Modules.Ref
{
    public partial class Contract : ModuleParent, IHostedApplication
    {
        int idAllowEditLanguage = 1,
            idAddNew = 195,
            idEdit = 196,
            idDelete = 197,
            idTransferIn = 198,
            idPrint = 199,
            idCopy = 200,
            idInsert = 210,
            idInsertHL = 211;
        int idToExcel = 269;

        string strAction = "";
        GridLayout layout = null;
        string _otherBusId = "";
        DataTable _ContractAddendum = null;
        FrmContractDetail _frmDetail = null;
        public Contract()
        {
            InitializeComponent();
            _strType = "Contract";

            //LimitAmt.Name = "LimitAmt";
            //LimitAmtOther.Name = "LimitAmtOther";
            //CIT.Name = "CIT";
            //VAT.Name = "VAT";
            //Addendum.Name = "Addendum";
            //ExpiryDate.Name = "ExpiryDate";
            //EffectiveDate.Name = "EffectiveDate";
            //SignDate.Name = "SignDate";
            //YearBudgetCode.Name = "YearBudgetCode";
            //OrderReq.Name = "OrderReq";
            //Status.Name = "Status";
            //aType.Name = "aType";
            //Remark1.Name = "Remark1";
            //Remark2.Name = "Remark2";
            //Remark3.Name = "Remark3";
            //MCApproval.Name = "MCApproval";
            //ActionRequired.Name = "ActionRequired";

            //lvDetail.SetLoadingMessage("Waiting...");
            dgvContract.SetLoadingMessage("Waiting...");
            _dgvList = dgvContract;
            _dgvFilter = gridFilter1;

            documentLink1.loadUrl();
        }

        bool _isCalculate = true;
        int intRow = 0;

        #region .::| Override Functions |::.
        protected override ErrorStatus validateForm(ref string sErr)
        {
            ErrorStatus result = ErrorStatus.SUCCESS;
            sErr = "";

            if (!string.IsNullOrEmpty(cboCreditor.Text) && string.Format("{0}", cboCreditor.Value) == "")
            {
                sErr += "Creditor is not in list, please check!\n";
                errProvider.SetError(cboCreditor, "Creditor is not in list!");
            }
            if (!string.IsNullOrEmpty(cboDepartment.Text) && string.Format("{0}", cboDepartment.SelectedValue) == "")
            {
                sErr += "Department is not in list, please check!\n";
                errProvider.SetError(cboDepartment, "Department is not in list!");
            }

            if (!string.IsNullOrEmpty(cboStatus.Text) && string.Format("{0}", cboStatus.SelectedValue) == "")
            {
                sErr += "Status is not in list, please check!\n";
                errProvider.SetError(cboStatus, "Status is not in list!");
            }
            if (!string.IsNullOrEmpty(cboVendor.Text) && string.Format("{0}", cboVendor.Value) == "")
            {
                sErr += "Status is not in list, please check!\n";
                errProvider.SetError(cboVendor, "Status is not in list!");
            }


            if (txtContract_PONo.Text.Trim() == "")
            {
                sErr += "Could not save blank Contract, please check!\n";
                errProvider.SetError(txtContract_PONo, "Could not save blank Contract");
                txtContract_PONo.Focus();
            }
            else errProvider.SetError(txtContract_PONo, "");

            if (txtCur.Text == "USD")
            {
                sErr += "Currency should not be USD, please check!\n";
                errProvider.SetError(txtCur, "Currency should not be USD");
            }
            else errProvider.SetError(txtCur, "");

            if (cboBudget.Text != "" && cboBudget.Value.ToString() != cboBudget.Text)
            {
                sErr += "Budget Code is not in list, please check!\n";
                errProvider.SetError(cboBudget, "Budget Code is not in list");
            }
            else errProvider.SetError(cboBudget, "");

            if (cboContractType.SelectedValue == null)
            {
                sErr += "Contract Type do not blank! please check!\n";
                errProvider.SetError(cboContractType, "Contract Type do not blank");
            }
            else errProvider.SetError(cboContractType, "");


            if (sErr != "") result = ErrorStatus.ERROR;

            //sErr = string.Format("{0}{1}", sErr, sWarn);

            return result;
        }

        protected override bool checkExists()
        {
            ContractControl ctr = new ContractControl();
            return ctr.IsExist(GetMainForm().PODInfo.Business_ID, txtContract_PONo.Text);

        }

        protected override string addRecord(bool isDraft = false)
        {
            string sErr = "";
            ContractControl ctr = new ContractControl();
            ContractDetailControl ctrDet = new ContractDetailControl();
            object trans = ctr.BeginTransaction(ref sErr);
            try
            {
                ctrDet.SetTransaction(trans);
                documentLink1._trans = trans;

                if (sErr == "") sErr = SaveContractDetail(GetMainForm().PODInfo.Business_ID, ctrDet);
                DTO.ContractInfo info = GetData();
                if (sErr == "") ctr.Add(GetMainForm().PODInfo.Business_ID, info, ref sErr);
                if (sErr == "") sErr = documentLink1.Update(info.Contract);
            }
            catch (Exception ex) { sErr = ex.Message; }
            finally
            {
                if (sErr == "") ctr.CommitTransaction(ref sErr);
                else ctr.RollbackTransaction(ref sErr);
            }

            return sErr;
        }
        protected override string updateRecord(bool isDraft = false)
        {
            string sErr = "";
            ContractControl ctr = new ContractControl();
            ContractDetailControl ctrDet = new ContractDetailControl();

            object trans = ctr.BeginTransaction(ref sErr);
            try
            {
                ctrDet.SetTransaction(trans);
                if (sErr == "") sErr = SaveContractDetail(GetMainForm().PODInfo.Business_ID, ctrDet);
                DTO.ContractInfo info = GetData();
                if (sErr == "") sErr = ctr.Update(GetMainForm().PODInfo.Business_ID, info);
                documentLink1._trans = trans;
                if (sErr == "") sErr = documentLink1.Update(info.Contract);
            }
            catch (Exception ex) { sErr = ex.Message; }
            finally
            {
                if (sErr == "") ctr.CommitTransaction(ref sErr);
                else ctr.RollbackTransaction(ref sErr);
            }
            return sErr;
        }
        protected override string delRecord()
        {
            string sErr = "";
            ContractControl ctr = new ContractControl();
            ContractDetailControl ctrDet = new ContractDetailControl();
            object trans = ctr.BeginTransaction(ref sErr);
            if (sErr == "") sErr = ctr.Delete(GetMainForm().PODInfo.Business_ID, txtContract_PONo.Text);
            documentLink1._trans = trans;
            if (sErr == "") sErr = documentLink1.Delete(txtContract_PONo.Text);
            BUS.ContractDetailControl ctrDetail = new ContractDetailControl();
            ctrDetail.SetTransaction(trans);
            if (sErr == "") sErr = ctrDetail.Delete(GetMainForm().PODInfo.Business_ID, txtContract_PONo.Text);

            if (sErr == "") ctr.CommitTransaction(ref sErr);
            else ctr.RollbackTransaction(ref sErr);
            return sErr;
        }

        protected override void afterUpdate()
        {
            RecalTotalContract();
        }
        protected override void afterAddNew()
        {
            RecalTotalContract();

        }
        protected override void afterDelete()
        {
            RecalTotalContract();
        }

        protected override void refreshForm(string str)
        {
            _isCalculate = false;
            gbPrimary.SuspendLayout();
            txtContract_PONo.Text = "";
            txtCIT.Value = 0;
            txtVAT.Value = 0;
            txtHVJOCCumulativeAmt.Value = 0;
            txtHVJOCremainingAmt.Value = 0;
            txtContractOwner.Text = "";
            txtDescrition.Text = "";
            cboDepartment.Text = "";

            txtSignDate.Text = "";
            txtEffectiveDate.Text = "";
            txtExpiryDate.Text = "";
            txtPymtTerm.Text = "";
            txtRemark1.Text = "";
            txtRemark2.Text = "";
            txtRemark3.Text = "";
            cboStatus.Text = "";
            cboBudget.Value = "";
            cboVendor.Value = "";
            txtCur.Text = "";
            txtUserReference.Text = "";
            cboContractType.SelectedValue = "";
            txtHVJOCContractValue.Value = 0;
            txtSharedContractValue.Value = 0;
            txtSharedCumulativeAmt.Value = 0;
            txtSharedRemainingAmt.Value = 0;
            txtHVJOCremainingAmt.Value = 0;
            cboCreditor.Value = "";
            txBudgetCode.Text = "";

            chkUncheckInInv.Checked = false;
            ClearContractDetail();
            documentLink1.Clear();
            gbPrimary.ResumeLayout(true);
            _isCalculate = true;
        }
        protected override void enableForm(bool val)
        {
            gbPrimary.SuspendLayout();
            txtContract_PONo.Enabled = val;
            txtContractOwner.Enabled = val;
            txtDescrition.Enabled = val;
            cboDepartment.Enabled = val;
            txtPymtTerm.Enabled = val;
            txtRemark1.Enabled = val;
            txtRemark2.Enabled = val;
            txtRemark3.Enabled = val;
            cboStatus.Enabled = val;
            cboBudget.Enabled = val;
            cboVendor.Enabled = val;
            txtCur.Enabled = val;
            txtUserReference.Enabled = val;
            cboContractType.Enabled = val;
            chkUncheckInInv.Enabled = val;
            //lvDetail.Enabled = val;
            //SetListViewReadOnly(val);
            //lvDetail.read
            // txtBudgetYear.Enabled = val;
            // txtBudgetYear.Enabled = val;
            cboBudget.Enabled = val;
            cboCreditor.Enabled = val;
            cboVendor.Enabled = val;
            //btAddDetail.Enabled = val;
            //btDelDetail.Enabled = val;
            documentLink1.SetEnabled(val);

            if (val == false)
            {
                foreach (Control x in gbPrimary.Controls)
                {
                    if (errProvider.GetError(x) != string.Empty) errProvider.SetError(x, "");
                }
            }

            gbPrimary.ResumeLayout(true);
        }

        //private void SetListViewReadOnly(bool val)
        //{
        //    foreach (ListViewItem it in lvDetail.Items)
        //    {
        //        foreach (ListViewItem.ListViewSubControlItem sub in it.SubItems)
        //        {
        //            if (sub != null)
        //            {
        //                sub.Control.Enabled = val;
        //            }
        //        }
        //    }
        //}
        protected override void loadRecord(object o)
        {
            if (o is DataRowView)
            {
                DTO.ContractInfo inf = new ContractInfo((DataRowView)o);
                SetData(inf);
            }
        }

        #endregion

        public void InitializeApplication()
        {
            disableSort();

        }

        public void SetObject(object obj)
        {

        }

        public void LoadCTDetailBudgetCode()
        {
            DataTable dtb = null;
            BudgetsControl bgCrt = new BudgetsControl();
            if (GetMainForm().PODInfo.Business_ID.Equals("HL"))
            {
                dtb = bgCrt.GetAll_Budgets(ref sErr);
            }
            else if (GetMainForm().PODInfo.Business_ID.Equals("HV"))
            {
                dtb = bgCrt.GetAll_Budgets1(ref sErr);
            }

            bisDetailBudget.DataSource = dtb;
            dtb.Columns.Add("YearBudgetCode", typeof(string));

            //foreach (DataRow row in dtb.Rows)
            //{
            //    row["YearBudgetCode"] = row["Year"].ToString() + "-" + row["BudgetCode"].ToString();
            //}
            //DataGridViewComboBoxColumn colm = dgvDetail.Columns["cboBudgetCodeDGV"] as DataGridViewComboBoxColumn;
            //colm.DataSource = bisDetailBudget;
            //colm.DisplayMember = "YearBudgetCode";
            //colm.ValueMember = "BudgetCode";
            //colm.ValueType = typeof(string);
            //colm.Tag = dtb;

        }
        DataTable _dtOrderReq;
        public void LoadComboBox()
        {
            BUS.PurchaseRequisitionControl purCtr = new BUS.PurchaseRequisitionControl();
            _dtOrderReq = purCtr.GetShortAll(MainForm.PODInfo.Business_ID, ref sErr);
            _dtOrderReq.Rows.InsertAt(_dtOrderReq.NewRow(), 0);

            //BUDGET
            BUS.BudgetsControl ctrcontr = new BUS.BudgetsControl();
            DataTable dtbgG = ctrcontr.GetAll(GetMainForm().PODInfo.Business_ID, ref sErr);

            var o = cboBudget.Value;
            cboBudget.MainForm = GetMainForm();
            cboBudget.Lookup = "bgC";
            cboBudget.DisplayMember = "aKey";
            cboBudget.ValueMember = "aKey";
            cboBudget.DataSource = dtbgG;
            if (o != null) cboBudget.Value = o;

            BUS.VENDORControl ctrVD = new BUS.VENDORControl();
            DataTable dtbVD = ctrVD.GetAll(GetMainForm().PODInfo.Business_ID, ref sErr);

            bisVendor.DataSource = dtbVD;

            o = cboVendor.Value;
            cboVendor.MainForm = GetMainForm();
            cboVendor.Lookup = "VendorCode";
            cboVendor.DisplayMember = "VendorCode";
            cboVendor.ValueMember = "VendorCode";
            cboVendor.DataSource = bisVendor;
            if (o != null) cboVendor.Value = o;
            // CREDIA

            o = cboCreditor.Value;
            cboCreditor.MainForm = GetMainForm();
            cboCreditor.Lookup = "VendorCode";
            cboCreditor.DisplayMember = "VendorName";
            cboCreditor.ValueMember = "VendorName";

            cboCreditor.DataSource = bisVendor;
            if (o != null) cboCreditor.Value = o;




            //Status
            DataTable stt = new DataTable();
            stt.Columns.Add("Name", typeof(string));
            stt.Columns.Add("Value", typeof(string));
            stt.Rows.Add("C-Close", "C");
            stt.Rows.Add("S-Suspense", "S");
            o = cboStatus.SelectedValue;
            cboStatus.DataSource = stt;
            cboStatus.ValueMember = "Value";
            cboStatus.DisplayMember = "Name";
            if (o != null) cboStatus.SelectedValue = o;
            //Contract Type

            DataTable ctt = new DataTable();
            ctt.Columns.Add("Name", typeof(string));
            ctt.Columns.Add("Value", typeof(string));
            ctt.Rows.Add("C-Contract", "C");
            ctt.Rows.Add("P-Purchase Order", "P");
            ctt.Rows.Add("S-Service Order", "S");
            o = cboContractType.SelectedValue;
            cboContractType.DataSource = ctt;
            cboContractType.ValueMember = "Value";
            cboContractType.DisplayMember = "Name";
            if (o != null) cboContractType.SelectedValue = o;

            string busId = GetMainForm().PODInfo.Business_ID;
            string connect = Properties.Settings.Default.HLConnectString;
            BUS.DepartmentsControl dptCtr = new DepartmentsControl();
            o = cboDepartment.SelectedValue;
            cboDepartment.DisplayMember = "CODE";
            cboDepartment.ValueMember = "CODE";
            cboDepartment.DataSource = dptCtr.getListInSub(busId, ref sErr, connect);

            if (o != null) cboDepartment.SelectedValue = o;
        }
        public void RefreshContract()
        {
            RecalTotalContract();
            LoadComboBox();
        }
        public void RecalTotalContract()
        {
            ContractControl ctCtr = new ContractControl();
            InvoiceRegisterControl ivCtr = new InvoiceRegisterControl();
            string sErr = "";
            string ex = "Contract='" + txtContract_PONo.Text + "'";
            double CTVALUE = 0, CTCUM = 0, CTREM = 0;
            double SHCTVALUE = 0, SHCTCUM = 0, SHCTREM = 0;
            DataTable dt = ivCtr.GetCond(GetMainForm().PODInfo.Business_ID, ex, ref sErr);
            if (GetMainForm().PODInfo.Business_ID == "HL")
            {

                ContractInfo ct = ctCtr.Get_Contract(txtContract_PONo.Text, ref sErr);
                CTVALUE = ct.LimitAmt; // Value of Contract in HL



                CTCUM = 0;
                foreach (DataRow row in dt.Rows)
                {
                    InvoiceRegisterInfo ivInfo = new InvoiceRegisterInfo(row);
                    CTCUM += ivInfo.Amt; // Total cum value of Contract in HL
                }
                CTREM = CTVALUE - CTCUM; // Remain value of Contract in HL

                // SHARE 

                ContractInfo ct1 = ctCtr.Get_Contract1(txtContract_PONo.Text, ref sErr);
                SHCTVALUE = ct1.LimitAmt + CTVALUE; // VALUE OF CONTRACTS IN HL HV

                SHCTCUM = CTCUM;
                DataRow[] dt1 = ivCtr.GetAll_InvoiceRegister1(ref sErr).Select(ex);
                foreach (DataRow row in dt1)
                {
                    InvoiceRegisterInfo ivInfo = new InvoiceRegisterInfo(row);
                    SHCTCUM += ivInfo.Amt; //TOTAL CUM VALUE OF CONTRACT IN HLHV
                }
                SHCTREM = SHCTVALUE - SHCTCUM; //REMAIN VALUE OF CONTRACT IN HLHV
            }
            else if (GetMainForm().PODInfo.Business_ID == "HV")
            {
                ContractInfo ct = ctCtr.Get_Contract1(txtContract_PONo.Text, ref sErr);
                CTVALUE = ct.LimitAmt; // Value of Contract in HL

                CTCUM = 0;
                foreach (DataRow row in dt.Rows)
                {
                    InvoiceRegisterInfo ivInfo = new InvoiceRegisterInfo(row);
                    CTCUM += ivInfo.Amt; // Total cum value of Contract in HL
                }
                CTREM = CTVALUE - CTCUM; // Remain value of Contract in HL

                // SHARE 

                ContractInfo ct1 = ctCtr.Get_Contract(txtContract_PONo.Text, ref sErr);
                SHCTVALUE = ct1.LimitAmt + CTVALUE; // VALUE OF CONTRACTS IN HL HV

                SHCTCUM = CTCUM;
                DataRow[] dt1 = ivCtr.GetAll_InvoiceRegister(ref sErr).Select(ex);
                foreach (DataRow row in dt1)
                {
                    InvoiceRegisterInfo ivInfo = new InvoiceRegisterInfo(row);
                    SHCTCUM += ivInfo.Amt; //TOTAL CUM VALUE OF CONTRACT IN HLHV
                }
                SHCTREM = SHCTVALUE - SHCTCUM; //REMAIN VALUE OF CONTRACT IN HLHV
            }

            txtHVJOCContractValue.Value = (decimal)CTVALUE;
            txtHVJOCCumulativeAmt.Value = (decimal)CTCUM;
            txtHVJOCremainingAmt.Value = (decimal)CTREM;

            txtSharedContractValue.Value = (decimal)SHCTVALUE;
            txtSharedCumulativeAmt.Value = (decimal)SHCTCUM;
            txtSharedRemainingAmt.Value = (decimal)SHCTREM;

        }

        public void LoadContractDetail()
        {
            string ctNo = txtContract_PONo.Text;
            string sErr = "";

            ContractDetailControl cdCrt = new ContractDetailControl();
            _ContractAddendum = cdCrt.GetAll(GetMainForm().PODInfo.Business_ID, ctNo, ref sErr);


        }

        //private void BindListView(DataTable dt)
        //{
        //    lvDetail.SuspendLayout();
        //    lvDetail.Items.Clear();
        //    foreach (DataRow r in dt.Rows)
        //    {
        //        AddNewDetail(r);
        //    }
        //    lvDetail.ResumeLayout(true);
        //}

        //private void AddNewDetail(DataRow r)
        //{
        //    ListViewItem objItem = new ListViewItem();
        //    objItem.Tag = r["ID"];
        //    for (int i = 0; i < lvDetail.Columns.Count; i++)
        //    {
        //        Control x = null;
        //        switch (lvDetail.Columns[i].Tag.ToString())
        //        {
        //            case "TextBox":
        //                x = new TextBox()
        //                {
        //                    // TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Text = r[lvDetail.Columns[i].Name].ToString(),
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };


        //                break;
        //            case "ComboBox":
        //                if (lvDetail.Columns[i].Name == "aType")
        //                {
        //                    x = new ComboBox()
        //                    {
        //                        //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                        DisplayMember = cboContractType.DisplayMember,
        //                        ValueMember = cboContractType.ValueMember,
        //                        Name = lvDetail.Columns[i].Name,
        //                        AutoCompleteMode = cboContractType.AutoCompleteMode,
        //                        DataSource = (cboContractType.DataSource as DataTable).Copy(),
        //                        DropDownStyle = cboContractType.DropDownStyle,
        //                        SelectedValue = r[lvDetail.Columns[i].Name],
        //                        Tag = objItem
        //                    };

        //                }
        //                else if (lvDetail.Columns[i].Name == "YearBudgetCode")
        //                {
        //                    x = new CustomControl.LookupBox()
        //                    {
        //                        //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                        DisplayMember = cboBudget.DisplayMember,
        //                        ValueMember = cboBudget.ValueMember,
        //                        Name = lvDetail.Columns[i].Name,
        //                        MainForm = cboBudget.MainForm,
        //                        Lookup = cboBudget.Lookup,
        //                        DataSource = (cboBudget.DataSource as DataTable).Copy(),
        //                        Value = r[lvDetail.Columns[i].Name],
        //                        Tag = objItem
        //                    };

        //                }
        //                else if (lvDetail.Columns[i].Name == "OrderReq")
        //                {
        //                    BUS.PurchaseRequisitionControl purCtr = new PurchaseRequisitionControl();
        //                    DataTable dtPurAA = purCtr.GetShortAll(GetMainForm().PODInfo.Business_ID, ref sErr);
        //                    dtPurAA.Rows.InsertAt(dtPurAA.NewRow(), 0);
        //                    x = new ComboBox()
        //                    {
        //                        //   TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                        DisplayMember = "InvNo",
        //                        ValueMember = "InvNo",
        //                        Name = lvDetail.Columns[i].Name,
        //                        AutoCompleteMode = AutoCompleteMode.SuggestAppend,
        //                        DataSource = dtPurAA,
        //                        SelectedValue = r[lvDetail.Columns[i].Name],
        //                        Tag = objItem
        //                    };

        //                }

        //                break;
        //            case "NumericUpDown":
        //                x = new NumericUpDown()
        //                {
        //                    //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Minimum = -999999999999,
        //                    Maximum = 999999999999,
        //                    DecimalPlaces = 2,
        //                    Value = r[lvDetail.Columns[i].Name] == DBNull.Value ? 0 : Convert.ToDecimal(r[lvDetail.Columns[i].Name]),
        //                    ThousandsSeparator = true,
        //                    HideButtons = true,
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };
        //                //((NumericUpDown)x).Enter += new EventHandler(Contract_Enter);
        //                break;
        //            case "DateTime":
        //                x = new CustomControl.DateTimeCustom()
        //                {
        //                    //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Value = r[lvDetail.Columns[i].Name] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(r[lvDetail.Columns[i].Name]),
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };
        //                break;
        //            case "CheckBox":
        //                x = new CheckBox()
        //                {
        //                    //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Checked = r[lvDetail.Columns[i].Name] == DBNull.Value ? false : Convert.ToBoolean(r[lvDetail.Columns[i].Name]),
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };
        //                break;
        //            default:
        //                x = new TextBox()
        //                {
        //                    //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Text = r[lvDetail.Columns[i].Name].ToString(),
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };
        //                break;
        //        }

        //        if (i == lvDetail.Columns.Count - 1)
        //        {
        //            x.LostFocus += delegate
        //            {
        //                NextItem(x.Tag);
        //            };
        //        }

        //        objItem.SubItems.Add(x);
        //    }

        //    lvDetail.Items.Add(objItem);
        //}

        //void Contract_Enter(object sender, EventArgs e)
        //{
        //    (sender as NumericUpDown).Select(0, (sender as NumericUpDown).ToString().Length);
        //}

        //private void NextItem(object o)
        //{
        //    ListViewItem it = o as ListViewItem;
        //    if (it.Index != lvDetail.Items.Count - 1)
        //    {
        //        ListViewItem next = lvDetail.Items[it.Index + 1];
        //        ListViewItem.ListViewSubControlItem nextControl = next.SubItems[0] as ListViewItem.ListViewSubControlItem;
        //        nextControl.Control.Focus();
        //    }
        //}

        private void checkCode()
        {
            errProvider.SetError(txtContract_PONo, "");
            if (txtContract_PONo.Text == "")
            {
                errProvider.SetError(txtContract_PONo, "Contract code cannot be blank, please check!");
            }
            else
            {
                BUS.ContractControl ctr = new BUS.ContractControl();
                if (GetMainForm().PODInfo.Business_ID == "HL")
                {
                    if (ctr.IsExist_Contract(txtContract_PONo.Text))
                    {
                        errProvider.SetError(txtContract_PONo, "This Contract is already existed, please check!");
                    }
                    else
                    {
                        errProvider.SetError(txtContract_PONo, "");
                    }
                }
                if (GetMainForm().PODInfo.Business_ID == "HV")
                {
                    if (ctr.IsExist_Contract1(txtContract_PONo.Text))
                    {
                        errProvider.SetError(txtContract_PONo, "This Contract is already existed, please check!");
                    }
                    else
                    {
                        errProvider.SetError(txtContract_PONo, "");
                    }
                }
            }
        }
        public void SetData(ContractInfo ct)
        {
            errProvider.SetError(txtContract_PONo, "");
            _isCalculate = false;
            gbPrimary.SuspendLayout();
            txtContract_PONo.Text = ct.Contract;
            txtCIT.Value = (decimal)ct.CIT;
            txtVAT.Value = (decimal)ct.VAT;
            txtHVJOCCumulativeAmt.Value = (decimal)ct.CummulativeAmt;
            txtHVJOCremainingAmt.Value = (decimal)ct.RemainingAmt;
            txtContractOwner.Text = ct.ContractHolder.ToString();
            txtDescrition.Text = ct.Desc.ToString();
            cboDepartment.Text = ct.Department.ToString();
            txtHVJOCContractValue.Value = (decimal)ct.LimitAmt;
            chkUncheckInInv.Checked = ct.SharedContract != 0;
            //Actual Cost
            txtSignDate.Text = (ct.SignDate == DateTime.MinValue ? "" : ct.SignDate.ToString("dd/MM/yyyy"));
            txtEffectiveDate.Text = (ct.EffectiveDate == DateTime.MinValue ? "" : ct.EffectiveDate.ToString("dd/MM/yyyy"));
            txtExpiryDate.Text = (ct.ExpiryDate == DateTime.MinValue ? "" : ct.ExpiryDate.ToString("dd/MM/yyyy"));
            txtPymtTerm.Text = ct.PaymentTerm.ToString();
            txtRemark1.Text = ct.Remark1.ToString();
            txtRemark2.Text = ct.Remark2.ToString();
            txtRemark3.Text = ct.Remark3.ToString();
            cboVendor.Value = ct.VendorCode;
            cboCreditor.Text = ct.VendorName;
            //MC Pro
            //Action Req
            cboStatus.SelectedValue = ct.Status;
            cboBudget.Value = ct.YearBudgetCode;
            //buggetyear
            //yearbuggetcode
            //vendor name
            txtCur.Text = ct.Cur.ToString();
            txBudgetCode.Text = ct.BudgetCode;

            txtUserReference.Text = ct.Cur.ToString();
            cboContractType.SelectedValue = ct.aType;
            //is link
            //a type
            documentLink1.reLoad(ct.Contract);
            LoadContractDetail();
            RecalTotalContract();
            gbPrimary.ResumeLayout();
            _isCalculate = true;
        }
        public ContractInfo GetData()
        {
            ContractInfo ct = new ContractInfo()
            {
                Contract = txtContract_PONo.Text,
                LimitAmt = (double)txtHVJOCContractValue.Value,
                CIT = (double)txtCIT.Value,
                VAT = (double)txtVAT.Value,
                CummulativeAmt = (double)txtHVJOCCumulativeAmt.Value,
                RemainingAmt = (double)txtHVJOCremainingAmt.Value,
                ContractHolder = txtContractOwner.Text,
                Desc = txtDescrition.Text.ToString(),
                Department = cboDepartment.Text.Trim(),
                SharedContract = chkUncheckInInv.Checked ? 1 : 0,

                SignDate = txtSignDate.Value,
                EffectiveDate = txtEffectiveDate.Value,
                ExpiryDate = txtExpiryDate.Value,
                PaymentTerm = (txtPymtTerm.Text == "" ? (short)0 : short.Parse(txtPymtTerm.Text.ToString())),
                Remark1 = txtRemark1.Text.ToString(),
                Remark2 = txtRemark2.Text.ToString(),
                Remark3 = txtRemark3.Text.ToString(),

                Status = cboStatus.SelectedValue + "",
                BudgetCode = txBudgetCode.Text,

                YearBudgetCode = cboBudget.Value.ToString(),
                VendorCode = cboVendor.Value.ToString(),
                VendorName = cboCreditor.Text + "",
                Cur = txtCur.Text.ToString(),
                UserRef = txtUserReference.Text.ToString(),
                isLink = (short)(documentLink1.getLinkCount()),
                aType = cboContractType.SelectedValue + ""
            };
            if (cboBudget.SelectedItem is DataRowView)
                ct.BudgetYear = Convert.ToInt32(((DataRowView)cboBudget.SelectedItem)["Year"]);

            return ct;
        }

        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            if (IsPermis(idAddNew)) objElements.Add(new HostedToolBarButton("Add New", "New", new IconResourceHandle("Add.png"), "C"));
            if (IsPermis(idAddNew) && IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Save", "Save", new IconResourceHandle("Save.png"), "S", false));
            if (IsPermis(idEdit)) objElements.Add(new HostedToolBarButton("Edit", "Edit", new IconResourceHandle("Edit.png"), "A"));
            objElements.Add(new HostedToolBarButton("Skip", "Skip", new IconResourceHandle("Reject.png"), "K", false));
            if (IsPermis(idDelete)) objElements.Add(new HostedToolBarButton("Delete", "Delete", new IconResourceHandle("Delete.png"), "X"));
            // if (IsPermis(idPrint)) objElements.Add(new HostedToolBarButton("Print", "To excel", new IconResourceHandle("Print.png"), "P"));
            if (IsPermis(idInsert)) objElements.Add(new HostedToolBarButton("Insert", "Insert to SunSystems", new IconResourceHandle("Add.png"), "I", false));
            if (IsPermis(idInsertHL)) objElements.Add(new HostedToolBarButton("InsertHL", "Insert to SunSystems " + _otherBusId, new IconResourceHandle("Add.png"), "H", false));
            if (IsPermis(idCopy)) objElements.Add(new HostedToolBarButton("Copy", "Duplicate Contract to " + _otherBusId, new IconResourceHandle("Copy.png"), "O"));
            if (IsPermis(idToExcel)) objElements.Add(new HostedToolBarButton("To Excel", "To Excel", new IconResourceHandle("Excel.png"), "P"));
            objElements.Add(new HostedToolBarButton("ContractReport", "Contract Report", new IconResourceHandle("Print.png"), "CR"));
            objElements.Add(new HostedToolBarButton("Refresh", new IconResourceHandle("Refresh.png"), "R"));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }

        private void copyToHLHV()
        {
            if (txtContract_PONo.Text == "")
            {
                MessageBox.Show("DO NOT duplicate blank contract! please check", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                return;
            }
            string otherBus = "HV";
            if (GetMainForm().PODInfo.Business_ID == "HV") otherBus = "HL";
            ContractControl ctr = new ContractControl();
            ContractDetailControl ctrDet = new ContractDetailControl();

            MessageBox.Show("Are you sure to duplicate this Contract " + txtContract_PONo.Text + " to Hoan Vu !", "Update", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
            {
                if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
                {
                    string sErr = "";
                    if (ctr.IsExist(otherBus, txtContract_PONo.Text))
                    {
                        MessageBox.Show("This Contract already exists in !" + otherBus);
                    }
                    else
                    {
                        errProvider.SetError(txtContract_PONo, "");
                        object trans = ctr.BeginTransaction(ref sErr);
                        ctrDet.SetTransaction(trans);
                        documentLink1._trans = trans;

                        //if (sErr == "") sErr = SaveContractDetail(otherBus, ctrDet);
                        DTO.ContractInfo info = GetData();
                        info.LimitAmt = 0;
                        info.CummulativeAmt = 0;
                        info.RemainingAmt = 0;
                        info.CIT = 0;
                        info.VAT = 0;
                        if (sErr == "") ctr.Add(otherBus, info, ref sErr);
                        documentLink1.Db = otherBus;
                        if (sErr == "") sErr = documentLink1.Update(info.Contract);
                        documentLink1.Db = GetMainForm().PODInfo.Business_ID; ;
                        if (sErr == "")
                        {
                            ctr.CommitTransaction(ref sErr);
                            enableForm(false);


                            RecalTotalContract();

                            reloadList();
                            MessageBox.Show("Your record is successfull duplicated!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                        }
                        else
                        {
                            MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                            ctr.RollbackTransaction(ref sErr);
                            Cancel = true;
                            strAction = "C";
                            _processStatus = "C";
                            SetupToolBar("C");
                        }
                    }
                }
                else if (((MessageBoxWindow)newSender).DialogResult == DialogResult.Cancel)
                {
                }
            }, false);

        }
        protected override void SetupToolBar(string strAction)
        {
            ToolBar tbarLocal = GetTbarLocal();
            bool on = true, off = false;
            if (tbarLocal == null) return;

            switch (strAction)
            {
                case "C":
                case "O":
                case "A":
                    foreach (ToolBarButton button in tbarLocal.Buttons)
                    {
                        if (button.Name == "R" || button.Name == "CR" || button.Name == "P") button.Enabled = on;
                        else if (!_btnProcess.Contains(button.Name))
                        {
                            if (button.Enabled != off) button.Enabled = off;
                        }
                        else { if (button.Enabled != on) button.Enabled = on; }
                    }
                    break;
                default:
                    foreach (ToolBarButton button in tbarLocal.Buttons)
                    {
                        if (button.Name == "R" || button.Name == "CR" || button.Name == "P") button.Enabled = on;
                        else if (!_btnProcess.Contains(button.Name))
                        {
                            if (button.Enabled != on) button.Enabled = on;
                        }
                        else { if (button.Enabled != off) button.Enabled = off; }
                    }

                    break;
            }

        }

        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            sErr = "";
            strAction = (string)objButton.Tag;

            BUS.ContractControl ctr = new BUS.ContractControl();
            switch (strAction)
            {
                case "C":
                    AddNew(txtContract_PONo);
                    break;
                case "A":
                    editRecord(txtContract_PONo);
                    break;
                case "S":
                    saveRecord(txtContract_PONo);
                    break;
                case "O":
                    copyToHLHV();
                    break;
                case "I":
                    insertToSunSytem(GetMainForm().PODInfo.Business_ID);
                    break;
                case "H":
                    insertToOther();
                    break;
                case "K":
                    skip();
                    break;
                case "X":
                    delete(txtContract_PONo);
                    break;

                case "R":
                    RefreshContract();

                    break;
                case "P":
                    export2Excel();
                    break;

                case "CR":
                    if (string.IsNullOrEmpty(txtContract_PONo.Text)) GetMainForm().SelectCategory("QRS", "id=ContractRpt01", "Contract Rpt");
                    else
                    {
                        SQLBuilder _sql = SQLBuilder.LoadSQLBuilderFromDataBase("ContractRpt01", "TVC", "");
                        foreach (Filter f in _sql.Filters)
                        {
                            if (f.Description == "Contract")
                            {
                                f.FilterFrom = txtContract_PONo.Text;
                                f.ValueFrom = txtContract_PONo.Text;
                                f.ValueTo = "";
                            }
                        }

                        ReportGenerator _report = new ReportGenerator(_sql, "ContractRpt01", "", MainForm.AppConnectString, MainForm.ServerPath + "ReportTemplate\\", MainForm.ServerPath + "Report\\", "");
                        ReportGenerator.User2007 = false;
                        _report.UserID = GetMainForm().PODInfo.USER_ID;
                        ExcelFile exfile = null;
                        try { exfile = _report.CreateReport(); }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                            return;
                        }
                        frmViewReport frmVi = new frmViewReport(_report.QdCode, GetMainForm());
                        frmVi.filename = _report.QdCode;
                        frmVi.Xls = exfile;
                        frmVi.BringToFront();
                        frmVi.Show();
                    }
                    break;
            }
            //  if (!Cancel) _processStatus = strAction;
            if (sErr == "") ThrowMsg("Command: " + _processStatus);
            //}
            //catch (Exception ex)
            //{
            //    ThrowMsg(ex.Message + Environment.NewLine + ex.Source);
            //}
        }

        private void insertToOther()
        {
            if (txtContract_PONo.Text == "")
            {
                MessageBox.Show("DO NOT copy blank contract! please check", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                return;
            }

            if (GetMainForm().PODInfo.Business_ID == "HL") insertToSunSytem("HV");
            else insertToSunSytem("HL");
        }

        private void insertToSunSytem(string BusId)
        {
            string db = Properties.Settings.Default.SUNHL;
            if (BusId == "HV") db = Properties.Settings.Default.SUNHV;
            if (txtContract_PONo.Text == "")
            {
                MessageBox.Show("DO NOT copy blank contract! please check", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning, false);
                return;
            }
            string sErr = "";

            DTO.ContractInfo info = GetData();
            ContractControl ctr = new ContractControl();
            bool exists = ctr.existsInSunSytem(info, ref sErr, MainForm.HLConnect, db);
            if (sErr != "")
            {
                MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                return;
            }
            if (exists)
            {
                MessageBox.Show("This contract code already exists in SunSystems!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                return;
            }

            if (info.Desc.Length > 30)
            {
                string confirmMsg = "Contract description length is more than 30 characters. It will be truncated?";
                MessageBox.Show(confirmMsg, "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, delegate(object newSender, EventArgs newArgs)
                {
                    if (((MessageBoxWindow)newSender).DialogResult == DialogResult.OK)
                    {
                        ctr.insertToSunSytem(info, ref sErr, MainForm.HLConnect, db);

                        if (sErr == "") MessageBox.Show("Insert to Sunsystem successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                        else MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                    }
                }, false);
            }
            else
            {
                ctr.insertToSunSytem(info, ref sErr, MainForm.HLConnect, db);

                if (sErr == "") MessageBox.Show("Insert to Sunsystem successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information, false);
                else MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
            }
        }

        public string SaveContractDetail(string busId, ContractDetailControl ctr)
        {
            string sErr = "";
            string ctNo = txtContract_PONo.Text;
            DTO.ContractDetailInfo info = new ContractDetailInfo();
            DataTable dt = info.ToDataTable();
            ctr.Delete(busId, ctNo);
            decimal limitAmt = 0;
            decimal limitOAmt = 0;
            decimal CIT = 0;
            decimal VAT = 0;
            for (var i = _ContractAddendum.Rows.Count - 1; i >= 0; i--)// ListViewItem it in lvDetail.Items)
            {
                if (sErr != "") return sErr;
                DataRow row = _ContractAddendum.Rows[i];

                info = new ContractDetailInfo(row);
                if (info.YearBudgetCode != "")
                {
                    int index = info.YearBudgetCode.IndexOf('-');
                    info.BudgetCode = info.YearBudgetCode.Substring(index + 1);
                    info.BudgetYear = Convert.ToInt32(info.YearBudgetCode.Substring(0, index));
                    //info.YearBudgetCode = (row.Cells["cboBudgetCodeDGV"] as DataGridViewComboBoxCell).FormattedValue.ToString();

                    try { info.BudgetYear = int.Parse(info.YearBudgetCode.Substring(0, 4).ToString()); }
                    catch (Exception ex) { sErr = ex.Message; }
                }
                else
                {
                    info.BudgetCode = "";
                    info.YearBudgetCode = "";
                    info.BudgetYear = 0;

                }
                info.Contract = ctNo;
                info.ID = ctr.Add(busId, info, ref sErr);
                limitAmt += (decimal)info.LimitAmt;
                limitOAmt += (decimal)info.LimitAmtOther;
                CIT += (decimal)info.CIT;
                VAT += (decimal)info.VAT;

                if (i == 0)
                {
                    cboBudget.Value = info.YearBudgetCode;
                    txtEffectiveDate.Value = info.EffectiveDate;
                    txtExpiryDate.Value = info.ExpiryDate;
                    txtSignDate.Value = info.SignDate;
                    //cboContractType.SelectedValue = info.aType;
                    txBudgetCode.Text = info.BudgetCode;
                    //txtRemark1.Text = info.Remark1;
                    //txtRemark2.Text = info.Remark2;
                    //txtRemark3.Text = info.Remark3;

                }


            }
            txtCIT.Value = CIT;
            txtVAT.Value = VAT;
            txtSharedContractValue.Value = txtSharedContractValue.Value - txtHVJOCContractValue.Value + limitAmt;
            txtSharedRemainingAmt.Value = txtSharedContractValue.Value - txtSharedCumulativeAmt.Value;
            txtHVJOCContractValue.Value = limitAmt;
            txtHVJOCremainingAmt.Value = limitAmt - txtHVJOCCumulativeAmt.Value;
            txtHVJOCContractValue.Value = limitAmt;


            return sErr;
        }

        private object GetValue(ListViewItem.ListViewSubItem listViewSubItem)
        {
            ListViewItem.ListViewSubControlItem tmp = listViewSubItem as ListViewItem.ListViewSubControlItem;
            if (tmp.Control is TextBox)
                return tmp.Control.Text;
            else if (tmp.Control is ComboBox)
                return ((ComboBox)tmp.Control).SelectedValue;
            else if (tmp.Control is NumericUpDown)
                return ((NumericUpDown)tmp.Control).Value;
            else if (tmp.Control is CustomControl.DateTimeCustom)
                return ((CustomControl.DateTimeCustom)tmp.Control).Value;
            else if (tmp.Control is CustomControl.LookupBox)
                return ((CustomControl.LookupBox)tmp.Control).Value;
            return DBNull.Value;
        }

        private void gridFilter1_GridFiterEvent(string strFilter, int year)// filter
        {
            string sErr = "";
            ContractControl ctCrt = new ContractControl();
            DataTable dtb = null;
            BUS.DepartmentsControl ctr = new DepartmentsControl();
            FormatDate();
            DataTable dt = ctr.GetAll(ref sErr, GetMainForm().PODInfo.ROLE_ID);
            string dpt = "";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i != 0) dpt += ",";
                dpt += string.Format("'{0}'", dt.Rows[i]["DPT_ID"]);
            }
            if (dpt != "")
            {
                dpt = string.Format("Department IN ({0})", dpt);
                if (strFilter != "") strFilter += " AND " + dpt;
                else strFilter = dpt;
            }
            if (GetMainForm().PODInfo.Business_ID == "HL")
                dtb = ctCrt.GetCond(strFilter, ref sErr);
            else if (GetMainForm().PODInfo.Business_ID == "HV")
                dtb = ctCrt.GetCond1(strFilter, ref sErr);
            if (!string.IsNullOrEmpty(gridFilter1.SortField))
            {
                dtb.DefaultView.Sort = gridFilter1.SortField + " " + gridFilter1.Direction;
            }
            bisContract.DataSource = dtb;

        }

        private void Contract_Load(object sender, EventArgs e)
        {
            if (GetMainForm().PODInfo.Business_ID == "HL") _otherBusId = "HV";
            else _otherBusId = "HV";

            documentLink1.Initialization(GetMainForm().PODInfo.Business_ID, _strType, "", GetMainForm());

            LoadComboBox();
            LoadCTDetailBudgetCode();
            SetLabel();
            refreshForm("");
            enableForm(false);
            _processStatus = "V";

        }
        private void SetLabel()
        {
            if (GetMainForm().PODInfo.Business_ID == "HL")
            {
                lbCtrValue.Text = "HLJOC Contract Value";
                lbCumValue.Text = "HLJOC Cumulative Amt";
                lbRemValue.Text = "HLJOC Remaining Amt";

            }
            else if (GetMainForm().PODInfo.Business_ID == "HV")
            {
                lbCtrValue.Text = "HVJOC Contract Value";
                lbCumValue.Text = "HVJOC Cumulative Amt";
                lbRemValue.Text = "HVJOC Remaining Amt";
            }
        }
        private void ClearContractDetail()
        {
            if (_ContractAddendum != null) _ContractAddendum.Rows.Clear();
            else
            {
                _ContractAddendum = new DTO.ContractDetailInfo().ToDataTable();
            }
        }
        private void Rebind()
        {
            gridFilter1.btnOK_Click(null, null);
        }

        private void disableSort()
        {

        }

        private DataRow GetBudgetCbo(DataTable tdb, string yearBudgetCode)
        {
            foreach (DataRow row in tdb.Rows)
            {
                if (row["YearBudgetCode"].ToString() == yearBudgetCode)
                {
                    return row;
                }
            }
            return null;
        }

        private void cboBudget_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cboBudget.SelectedItem is DataRowView)
            {
                txBudgetCode.Text = ((DataRowView)cboBudget.SelectedItem)["BudgetCode"].ToString();
                if (_ContractAddendum != null && _ContractAddendum.Rows.Count > 0)
                {
                    _ContractAddendum.Rows[0]["BudgetCode"] = cboBudget.Value;

                }
            }
        }

        //private void btAddDetail_Click(object sender, EventArgs e)
        //{
        //    VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
        //    InsertTopDetail(new ContractDetailInfo());

        //    (lvDetail.Items[0].SubItems[0] as ListViewItem.ListViewSubControlItem).Control.Focus();

        //}
        //private void InsertTopDetail(ContractDetailInfo contractDetailInfo)
        //{
        //    InsertTopDetail(contractDetailInfo.ToDataRow(contractDetailInfo.ToDataTable()));
        //}

        //private void InsertTopDetail(DataRow r)
        //{
        //    ListViewItem objItem = new ListViewItem();
        //    objItem.Tag = r["ID"];
        //    for (int i = 0; i < lvDetail.Columns.Count; i++)
        //    {
        //        Control x = null;
        //        switch (lvDetail.Columns[i].Tag.ToString())
        //        {
        //            case "TextBox":
        //                x = new TextBox()
        //                {
        //                    // TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Text = r[lvDetail.Columns[i].Name].ToString(),
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };


        //                break;
        //            case "ComboBox":
        //                if (lvDetail.Columns[i].Name == "aType")
        //                {
        //                    x = new ComboBox()
        //                    {
        //                        //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                        DisplayMember = cboContractType.DisplayMember,
        //                        ValueMember = cboContractType.ValueMember,
        //                        Name = lvDetail.Columns[i].Name,
        //                        AutoCompleteMode = cboContractType.AutoCompleteMode,
        //                        DataSource = (cboContractType.DataSource as DataTable).Copy(),
        //                        DropDownStyle = cboContractType.DropDownStyle,
        //                        SelectedValue = r[lvDetail.Columns[i].Name],
        //                        Tag = objItem
        //                    };

        //                }
        //                else if (lvDetail.Columns[i].Name == "YearBudgetCode")
        //                {
        //                    x = new CustomControl.LookupBox()
        //                    {
        //                        //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                        DisplayMember = cboBudget.DisplayMember,
        //                        ValueMember = cboBudget.ValueMember,
        //                        Name = lvDetail.Columns[i].Name,
        //                        MainForm = cboBudget.MainForm,
        //                        Lookup = cboBudget.Lookup,
        //                        DataSource = (cboBudget.DataSource as DataTable).Copy(),
        //                        Value = r[lvDetail.Columns[i].Name],
        //                        Tag = objItem
        //                    };

        //                }
        //                else if (lvDetail.Columns[i].Name == "OrderReq")
        //                {
        //                    BUS.PurchaseRequisitionControl purCtr = new PurchaseRequisitionControl();
        //                    DataTable dtPurAA = purCtr.GetShortAll(GetMainForm().PODInfo.Business_ID, ref sErr);
        //                    dtPurAA.Rows.InsertAt(dtPurAA.NewRow(), 0);
        //                    x = new ComboBox()
        //                    {
        //                        //   TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                        DisplayMember = "InvNo",
        //                        ValueMember = "InvNo",
        //                        Name = lvDetail.Columns[i].Name,
        //                        AutoCompleteMode = AutoCompleteMode.SuggestAppend,
        //                        DataSource = dtPurAA,
        //                        SelectedValue = r[lvDetail.Columns[i].Name],
        //                        Tag = objItem
        //                    };

        //                }

        //                break;
        //            case "NumericUpDown":
        //                x = new NumericUpDown()
        //                {
        //                    //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Minimum = -999999999999,
        //                    Maximum = 999999999999,
        //                    DecimalPlaces = 2,
        //                    Value = r[lvDetail.Columns[i].Name] == DBNull.Value ? 0 : Convert.ToDecimal(r[lvDetail.Columns[i].Name]),
        //                    ThousandsSeparator = true,
        //                    HideButtons = true,
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };
        //                //((NumericUpDown)x).Enter += new EventHandler(Contract_Enter);
        //                break;
        //            case "DateTime":
        //                x = new CustomControl.DateTimeCustom()
        //                {
        //                    //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Value = r[lvDetail.Columns[i].Name] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(r[lvDetail.Columns[i].Name]),
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };
        //                break;
        //            case "CheckBox":
        //                x = new CheckBox()
        //                {
        //                    //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Checked = r[lvDetail.Columns[i].Name] == DBNull.Value ? false : Convert.ToBoolean(r[lvDetail.Columns[i].Name]),
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };
        //                break;
        //            default:
        //                x = new TextBox()
        //                {
        //                    //  TabIndex = lvDetail.Items.Count * lvDetail.Columns.Count + i,
        //                    Text = r[lvDetail.Columns[i].Name].ToString(),
        //                    Name = lvDetail.Columns[i].Name,
        //                    Tag = objItem
        //                };
        //                break;
        //        }
        //        if (i == lvDetail.Columns.Count - 1)
        //        {
        //            x.LostFocus += delegate
        //            {
        //                NextItem(x.Tag);
        //            };
        //        }
        //        objItem.SubItems.Add(x);
        //    }
        //    lvDetail.Items.Insert(0, objItem);
        //    //lvDetail.Items.Add();

        //}
        //private void AddNewDetail(ContractDetailInfo contractDetailInfo)
        //{
        //    AddNewDetail(contractDetailInfo.ToDataRow(contractDetailInfo.ToDataTable()));
        //}

        //private void btDelDetail_Click(object sender, EventArgs e)
        //{
        //    VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
        //    for (int i = lvDetail.CheckedItems.Count - 1; i >= 0; i--)
        //    {
        //        lvDetail.Items.Remove(lvDetail.CheckedItems[i] as ListViewItem);
        //    }
        //}

        //private void lvDetail_GotFocus(object sender, EventArgs e)
        //{
        //    if (lvDetail.Items.Count > 0)
        //    {
        //        ListViewItem.ListViewSubControlItem subControl = lvDetail.Items[0].SubItems[0] as ListViewItem.ListViewSubControlItem;
        //        subControl.Control.Focus();
        //    }
        //}

        private void cboBudget_Leave(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cboVendor.Text) && cboBudget.Value + "" == "")
            {
                MessageBox.Show(" Please select from the list ", false);
            }
        }

        private void cboVendor_SelectedValueChanged(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (cboVendor.SelectedItem is DataRowView && cboVendor.Focused)
            {
                cboCreditor.Text = ((DataRowView)cboVendor.SelectedItem)["VendorName"].ToString();
                cboCreditor.Focus();
            }
        }

        private void cboCreditor_SelectedValueChanged(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (cboCreditor.SelectedItem is DataRowView && cboCreditor.Focused)
            {
                cboVendor.Value = ((DataRowView)cboCreditor.SelectedItem)["VendorCode"].ToString();
            }
        }

        private void btDetail_Click(object sender, EventArgs e)
        {
            ShowContractAddendum(txtDescrition.Enabled);
        }

        private void ShowContractAddendum(bool p)
        {
            if (_frmDetail == null)
            {
                _frmDetail = new FrmContractDetail();
                _frmDetail.DtBudget = cboBudget.DataSource as DataTable;
                _frmDetail.DtOrderReq = _dtOrderReq;
                _frmDetail.SetReadOnly(!p);
                _frmDetail.DataSource = _ContractAddendum;
                _frmDetail.FormClosed += new Gizmox.WebGUI.Forms.Form.FormClosedEventHandler(_frmDetail_FormClosed);
                _frmDetail.MainForm = GetMainForm();
                _frmDetail.Show(btDetail);
            }
            else
            {
                _frmDetail.BringToFront();
            }
        }

        void _frmDetail_FormClosed(object sender, FormClosedEventArgs e)
        {
            _frmDetail = null;
        }

        //private void cboCreditor_Leave(object sender, EventArgs e)
        //{
        //    if (cboCreditor.Text != null && cboCreditor.Text.Trim() != "")
        //    {
        //        if (cboCreditor.Value.ToString().Trim() == "")
        //        {
        //            cboCreditor.Focus();
        //            MessageBox.Show(" Please select from the list ", false);
        //        }
        //    }
        //}

        //private void cboVendor_Leave(object sender, EventArgs e)
        //{
        //    if (cboVendor.Text != null && cboVendor.Text.Trim() != "")
        //    {
        //        if (cboVendor.Value.ToString().Trim() == "")
        //        {
        //            cboVendor.Focus();
        //            MessageBox.Show(" Please select from the list ", false);
        //        }
        //    }
        //}



        //private void dgvDetail_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        //{
        //    if (e.Control is ComboBox)
        //    {
        //        ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
        //        ((ComboBox)e.Control).AutoCompleteMode = AutoCompleteMode.SuggestAppend;
        //        ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
        //    }
        //}

        //private void dgvDetail_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        //{
        //    if (dgvDetail.IsCurrentCellDirty)
        //    {
        //        dgvDetail.CommitEdit(DataGridViewDataErrorContexts.Commit);
        //    }
        //}


    }
}